package scala.day02

import scala.io.Source

object Demo11WordCount {
  def main(args:Array[String]):Unit = {
    //1、读取文件并转换成集合
    val lines: List[String] = Source.fromFile("data/words.txt").getLines().toList
    println(lines)
    //2.将每一行的单词拆分出来
    val words: List[String] = lines.flatMap((line:String)=>line.split(","))
    println(words)
    //3.按照单词进行分组
    //key是单词，value是单词的集合
    val group: Map[String, List[String]] = words.groupBy((word:String)=>word)
    println(group)
    //4.统计单词进行分组
   val count = group.map((kv:(String,List[String]))=>{
     //当前单词
     val word: String = kv._1
     //单词的集合
     val ws: List[String] = kv._2
     //单词的数量
     val num: Int = ws.length
     //返回一个二元组
     (word,num)
   })
    count.foreach(println)
    println("*"*20)
    Source.fromFile("data/words.txt")
      .getLines()//获取所有行
      .toList//转换成集合
      .flatMap(_.split(","))//将每一行的单词拆分出来
      .groupBy(w=>w)//按照单词分组
      .mapValues(_.length)//统计单词数量
      .foreach(println)
  }
}
